package cn.com.oyat.idea.controller;

import cn.com.oyat.idea.common.AjaxResult;
import cn.com.oyat.idea.model.LicenseModel;
import cn.com.oyat.idea.service.LicenseService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequiredArgsConstructor
public class RegController {

    private final LicenseService licenseService;
    private final Semaphore semaphore = new Semaphore(5);

    /**
     * 生成证书
     * @param licenseName 证书名称
     * @param prefix 前缀
     * @param suffix 后缀
     * @return
     */
    @GetMapping("/generateLicense")
    public AjaxResult list(@RequestParam(value = "licenseName",required=false) String licenseName,
                           @RequestParam(value = "prefix",required=false) String prefix,
                           @RequestParam(value = "suffix",required=false) String suffix
    ) {
        System.out.println("开始生成证书");
        if (!semaphore.tryAcquire()) {
            return AjaxResult.error("任务队列已满，请稍后再试");
        }
        if(StrUtil.isBlank(prefix)&&StrUtil.isBlank(suffix)){
            if (StrUtil.isBlank(licenseName) && licenseName.length() > 6) {
                return AjaxResult.error("证书名称不能为空,或者不能大于6个字符");
            }
        }
        try {
            LicenseModel licenseModel = new LicenseModel();
            //创建随机
            licenseModel.setLicenseId(RandomUtil.randomStringUpper(6));
            licenseModel.setLicenseeName(licenseName);
            licenseModel.setPrefix(prefix);
            licenseModel.setSuffix(suffix);
            //创建2099年12月31日证书
            //licenseService.generateCert(licenseModel);
            licenseService.generateLicenseFile(licenseModel);
            // 生成证书和许可证
//            Map<String, String> files = new HashMap<>();
//            files.put("power.conf", CertGenerator.generatePowerConf(requestId));
//            files.put("license.txt", LicenseGenerator.generateLicense(requestId));

            return AjaxResult.successData(200, licenseModel);
        } catch (Exception e) {
            return AjaxResult.error("生成失败");
        } finally {
            System.out.println("释放许可");
            // 释放许可
            semaphore.release();
        }
    }

    @GetMapping("/zipLicense")
    public  ResponseEntity<byte[]> zipLicense(@RequestParam(value = "licenseName",required=false) String licenseName,
                           @RequestParam(value = "prefix",required=false) String prefix,
                           @RequestParam(value = "suffix",required=false) String suffix
    ) throws Exception {
        System.out.println("ZIP开始生成证书");
        if (!semaphore.tryAcquire()) {
            throw new Exception("任务队列已满，请稍后再试");
        }
        if(StrUtil.isBlank(prefix)&&StrUtil.isBlank(suffix)){
            if (StrUtil.isBlank(licenseName) && licenseName.length() > 6) {
                throw new Exception("证书名称不能为空,或者不能大于6个字符");
            }
        }
        try {
            LicenseModel licenseModel = new LicenseModel();
            //创建随机
            licenseModel.setLicenseId(RandomUtil.randomStringUpper(6));
            licenseModel.setLicenseeName(licenseName);
            licenseModel.setPrefix(prefix);
            licenseModel.setSuffix(suffix);
            //创建2099年12月31日证书
            //licenseService.generateCert(licenseModel);
            licenseService.generateLicenseFile(licenseModel);
            // 生成证书和许可证
            Map<String, String> files = new HashMap<>();
            files.put("power.conf", licenseModel.getPower());
            files.put("license.txt", licenseModel.getLicensee());
            byte[] zipData = createZipArchive(files);
            System.out.println("ZIP生成证书成功");

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "license_package.zip");

            System.out.println("ZIP生成证书成功");
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(zipData);

        } catch (Exception e) {
            throw new Exception("生成失败");
        } finally {
            System.out.println("释放许可");
            // 释放许可
            semaphore.release();
        }
    }

    private byte[] createZipArchive(Map<String, String> files) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ZipOutputStream zos = new ZipOutputStream(baos)) {

            for (Map.Entry<String, String> entry : files.entrySet()) {
                ZipEntry zipEntry = new ZipEntry(entry.getKey());
                zos.putNextEntry(zipEntry);
                zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
                zos.closeEntry();
            }
            return baos.toByteArray();
        }
    }
}
